<template>
  <page-wrap scrollType="bs" :initBs="initBs" :load="loadData">
    <template #RollingLow>
      <div class="booklist-header">
        <TimeChange @select="onSelectTimeChange"></TimeChange>
      </div>
      <z-tab
        v-model:active="tabActive"
        :tabList="formattedTabList"
        top="2"
        @click-tab="onClickTab"
      ></z-tab>
      <z-search
        placeholder="请输入会员姓名/手机号"
        @query="onQuery"
        @update:model-value="onUpdateVal"
      ></z-search>
    </template>
    <div class="booklist-container">
      <div class="booklist-container-main">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
        >
          <div class="booklist-main-item" v-for="(v, k) in list" :key="k">
            <div class="item-header">
              <div class="item-header-big">{{ v.memberName }}</div>
              <div class="item-header-left">{{ v.memberMobile }}</div>
              <div class="item-header-right" v-if="v.state == 0">已取消</div>
              <div class="item-header-right" v-if="v.state == 1">已预订</div>
              <div
                class="item-header-right"
                v-if="v.state == 2 || v.state == 3"
              >
                已开台
              </div>
            </div>
            <div class="item-main">
              <div class="item-main-top">
                <!-- <div class="main-top-title"></div> -->
                <div class="main-top-value">预订号：{{ v.reserveCode }}</div>
              </div>
              <div class="item-main-table">
                {{ v.roomName }}
              </div>
              <ul class="item-main-center">
                <li class="main-center-li">
                  <div class="li-left">
                    <span class="li-left-title">人数：</span
                    ><span class="li-left-value">{{ v.peopleNumber }}人</span>
                  </div>
                  <div class="li-right">
                    <span class="li-right-title">到店时间：</span
                    ><span class="li-right-value"
                      >{{ dayjs(v.reserveTime).format('YYYY-MM-DD') }}
                      {{ dayjs(v.reserveTime).format('HH:mm') }}</span
                    >
                  </div>
                </li>
                <li class="main-center-li">
                  <div class="li-left">
                    <span class="li-left-title">订台人：</span
                    ><span class="li-left-value" style="color: #ffaa00">{{
                      v.maintainUserName
                    }}</span>
                  </div>
                  <div class="li-right">
                    <span class="li-right-title" v-if="v.state == 0"
                      >取消时间：</span
                    >
                    <span class="li-right-title" v-if="v.state == 1"
                      >预留时间：</span
                    >
                    <span
                      class="li-right-title"
                      v-if="v.state == 2 || v.state == 3"
                      >开台时间：</span
                    >
                    <span class="li-right-value">
                      {{ dayjs(v.keepFullTime).format('YYYY-MM-DD') }}
                      {{ dayjs(v.keepFullTime).format('HH:mm') }}
                    </span>
                  </div>
                </li>
              </ul>
              <div class="item-main-low">
                <span class="low-note-title">备注：</span
                ><span class="low-note-value">{{ v.remark }}</span>
              </div>
            </div>
            <div class="item-footer" v-if="v.state == 1">
              <div class="item-footer-button" @click="onPanel('cancel', v)">
                取消预订
              </div>
              <div class="item-footer-button" @click="onPanel('edit', v)">
                编辑
              </div>
              <div
                class="item-footer-button highlight"
                @click="onPanel('open', v)"
              >
                开台
              </div>
            </div>
          </div>
        </van-list>
      </div>
    </div>
  </page-wrap>

  <!-- 取消预订弹窗 -->
  <z-popup
    v-model:show="cancelShow"
    closeable
    :style="{ width: '334px' }"
    title="取消预订"
  >
    <div class="popup-cancel">
      <div class="cancelPre-main" @click="cancelPickerShow = true">
        <div class="cancelPre-main-left">取消原因</div>
        <div class="cancelPre-main-right">
          <div class="cancelPre-right-icon"></div>
          {{ cancelReason }}
        </div>
      </div>
      <van-field
        v-model="cancelBookForm.remark"
        name="备注"
        label="备注"
        placeholder="请输入备注"
        autocomplete="off"
      />
      <z-button
        @click="onSubmitCancel"
        :style="{ width: '160px', margin: '30px auto 0' }"
        >确定取消</z-button
      >
    </div>
  </z-popup>

  <!-- 取消原因选择器 -->
  <z-picker
    v-model:show="cancelPickerShow"
    :columns="cancelColumns"
    title="取消原因"
    @confirm="onConfirmCancel"
  />
</template>
<script setup>
import dayjs from 'dayjs'
import Api from '@/api'
import { transformArrayProps } from '@/lib/util.js'
import useConfigStore from '@/store/config'
import { showToast } from 'vant'

import { transformWorkTime } from '@/utils/chenhao'
import useAppStore from '@/store/app'
const appStore = useAppStore()

import v_image_add from '@/assets/svg/common/v_image_add_black.svg'

const router = useRouter()
const configStore = useConfigStore()

const list = ref([])
const loading = ref(false)
const finished = ref(false)
const cancelShow = ref(false)
const cancelPickerShow = ref(false)
const cancelColumns = ref([])
const cancelReason = ref('请选择')
const cancelItem = ref({})
const tabActive = ref(0)
const summary = ref({
  totalCount: 0,
  reserveCount: 0,
  finishCount: 0,
  cancelCount: 0
})
const tabList = reactive([
  { name: '全部', countKey: 'totalCount' },
  { name: '已预订', countKey: 'reserveCount' },
  { name: '已开台', countKey: 'finishCount' },
  { name: '已取消', countKey: 'cancelCount' }
])
// 格式化标签列表，将计数值动态添加到标签名称中
const formattedTabList = computed(() => {
  return tabList.map(tab => {
    return { name: `${tab.name}(${summary.value[tab.countKey]})` }
  })
})
const initBs = ref(0)

//表单
const postForm = reactive({
  key: '',
  currentDate_Start: transformWorkTime('今日',appStore.getReportTime.startTime,appStore.getReportTime.endTime)[0],
  currentDate_End: transformWorkTime('今日',appStore.getReportTime.startTime,appStore.getReportTime.endTime)[1],
  pageIndex: 1,
  pageSize: 15,
  state: ''
})

const cancelBookForm = reactive({
  roomCode: '',
  reserveCode: '',
  cancelReason: undefined,
  remark: ''
})

const onClickTab = e => {
  switch (e.name) {
    case 0:
      postForm.state = ''
      break
    case 1:
      postForm.state = 1
      break
    case 2:
      postForm.state = 2
      break
    case 3:
      postForm.state = 0
      break
  }
  loadData(true)
}
const allPostForm = reactive({
  currentDate_Start: transformWorkTime('今日',appStore.getReportTime.startTime,appStore.getReportTime.endTime)[0],
  currentDate_End: transformWorkTime('今日',appStore.getReportTime.startTime,appStore.getReportTime.endTime)[1],
})
const onSelectTimeChange = (startTime, endTime) => {
  postForm.currentDate_Start = startTime
  postForm.currentDate_End = endTime
  loadData(true)
  allPostForm.currentDate_Start = startTime
  allPostForm.currentDate_End = endTime
  loadStateCount()
}

// 查询参数
const onQuery = val => {
  postForm.key = val
  loadData(true)
}

// 实时搜索
const searchTimer = ref(null)
const onUpdateVal = val => {
  clearTimeout(unref(searchTimer))
  searchTimer.value = setTimeout(() => {
    postForm.key = val
    loadData(true)
  }, 500)
}

// 选择取消原因
const onConfirmCancel = e => {
  cancelReason.value = e.selectedOptions[0].text
  cancelBookForm.cancelReason = e.selectedOptions[0].text
  cancelPickerShow.value = false
}

// 确认取消
const onSubmitCancel = () => {
  if (!cancelBookForm.cancelReason) {
    showToast('请选择取消原因')
    return
  }
  cancelBookForm.roomCode = unref(cancelItem).roomCode
  cancelBookForm.reserveCode = unref(cancelItem).reserveCode
  Api.Common.AppObjProcess.Do({
    functionName: 'reserveCancel',
    contentData: cancelBookForm
  }).then(res => {
    showToast('取消成功')
    cancelShow.value = false
    cancelReason.value = '请选择'
    loadData(true)
  })
}

// 加载
const loadData = async function (refresh = false) {
  if (refresh === true) {
    finished.value = false
    postForm.pageIndex = 1
    list.value = []
  }
  loading.value = true
  const resp = await Api.Common.AppObjProcess.Do({
    functionName: 'getReserveList',
    contentData: postForm
  })
  const nowList = resp.result
  // console.log(nowList)
  if (refresh === true) {
    if (nowList.length !== postForm.pageSize) {
      finished.value = true
    }
  }
  Array.prototype.push.apply(list.value, nowList)
  if (nowList.length > 0) {
    postForm.pageIndex++
  } else {
    finished.value = true
  }
  loading.value = false
  initBs.value++
}

// 控制台
const onPanel = (type, v) => {
  switch (type) {
    case 'cancel':
      cancelShow.value = true
      cancelItem.value = v
      break
    case 'edit':
      router.push({
        path: '/book/form',
        query: {
          reserveCode: v.reserveCode,
          source: 'edit'
        }
      })
      break
    case 'open':
      router.push({
        path: '/open/confirm',
        query: {
          reserveCode: v.reserveCode,
          source: 'open'
        }
      })
      break
  }
}
const loadStateCount = async function () {
  // 获取预订各状态数量统计
  const resp = await Api.Common.AppObjProcess.Do({
    functionName: 'GetReserveStateCount',
    contentData: allPostForm
  })
  summary.value = resp
}
// 初始化
const onInit = () => {
  loadData(true)
  const transCancel = [
    ['name', 'text'],
    ['code', 'value']
  ]
  cancelColumns.value = transformArrayProps(configStore.cancelList, transCancel)
  loadStateCount()
}
onInit()
</script>
<style scoped lang="scss">
.booklist-header {
  // padding-bottom: 10px;
}
.booklist-container {
  padding: 0 12px;

  .booklist-container-main {
  }

  .booklist-container-footer {
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    padding: 0 12px 20px;

    .booklist-footer-btn {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .booklist-footer-icon {
      width: 18px;
      height: 18px;
      margin-right: 8px;
    }
  }
}
.booklist-main-item {
  margin-bottom: 10px;
  background: #28282e;
  border-radius: 8px;

  .item-header {
    display: flex;
    justify-content: space-between;
    // align-items: center;
    padding: 15px 12px;
    border-bottom: 1px solid #383840;

    .item-header-big {
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffffff;
      line-height: 18px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      max-width: 16ch;
    }

    .item-header-left {
      flex: 1;
      font-size: 13px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #cccccc;
      line-height: 13px;
      display: flex;
      align-items: flex-end;
      padding-bottom: 2px;
      padding-left: 6px;
    }

    .item-header-right {
      font-size: 13px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #999999;
      line-height: 13px;
      display: flex;
      align-items: center;
    }
  }

  .item-main {
    padding: 12px 24px;

    .item-main-top {
      display: flex;
      align-items: center;
      padding-bottom: 20px;

      .main-top-title {
        font-size: 18px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #ffffff;
        line-height: 18px;
      }

      .main-top-value {
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #cccccc;
        line-height: 14px;
      }
    }
    .item-main-table {
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 24px;
      color: #ffffff;
      line-height: 24px;
      padding-bottom: 20px;
    }
    .item-main-center {
      .main-center-li {
        list-style: none;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-bottom: 12px;

        .li-left {
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 500;
          line-height: 14px;

          .li-left-title {
            color: #cccccc;
          }

          .li-left-value {
            color: #ffffff;
          }
        }

        .li-right {
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 500;
          line-height: 14px;

          .li-right-title {
            color: #cccccc;
          }

          .li-right-value {
            color: #ffffff;
          }
        }
      }
    }

    .item-main-low {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #cccccc;
      line-height: 14px;
      .low-note-title {
        color: #cccccc;
      }

      .low-note-value {
        color: #ffffff;
        word-wrap: break-word;
      }
    }
  }

  .item-footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 12px 12px 14px;
    border-top: 1px solid #383840;

    .item-footer-button {
      width: 80px;
      background: #5c5c66;
      padding: 8px 0;
      text-align: center;
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffffff;
      line-height: 14px;
      margin-right: 10px;

      &.highlight {
        background: linear-gradient(0deg, #cca67a, #fff4d9);
        color: #260c04;
      }
    }
  }
}

.popup-cancel {
  padding: 12px 20px 20px 20px;

  .cancelPre-main {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #505059;
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 500;
    line-height: 16px;

    .cancelPre-main-left {
      color: #cccccc;
      padding: 14px 0 17px 0px;
    }

    .cancelPre-main-right {
      color: #cccccc;
      margin-left: 12px;
      overflow: hidden;
      position: relative;
      padding: 14px 17px 17px 0;

      .cancelPre-right-icon {
        width: 10px;
        height: 100%;
        position: absolute;
        right: 0px;
        top: 0px;
        background-image: url('@/assets/svg/confirm/v_confirm-triangle.svg');
        background-repeat: no-repeat;
        background-position: center center;
        background-size: 10px 6px;
      }
    }
  }
  // 取消预订的备注居右
  :deep(.van-field__control) {
    text-align: right;
    color: #cccccc;
  }

  // 取消预订的备注外边距
  :deep(.van-cell) {
    width: auto;
  }

  // 取消预订备注背景
  :deep(.van-field) {
    background: #45454d;
    border: none;
    padding: 17px 0px 17px 0px;
    border-bottom: 1px solid #505059;
  }

  :deep(.van-field__label) {
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #cccccc;
    line-height: 16px;
  }

  :deep(.van-cell:after) {
    border-bottom: 0;
  }
}
</style>
